package com.example.demo.api;


import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;

import com.example.demo.MyApplication;
import com.example.demo.utils.LogUtils;
import com.example.demo.utils.TokenManager;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {

    private static Retrofit retrofit;
    private static final String BASE_URL = "http://172.16.0.10:8080";  // 替换为你的API基础地址

    private RetrofitClient() {
        // 私有构造函数，确保单例模式
    }

    public static Retrofit getInstance() {
        if (retrofit == null) {
            synchronized (RetrofitClient.class) {
                if (retrofit == null) {
                    // 创建 OkHttpClient
                    OkHttpClient okHttpClient = new OkHttpClient.Builder()
                            .addInterceptor(createRequestInterceptor())  // 请求拦截器
                            .addInterceptor(createResponseInterceptor()) // 响应拦截器
                            .addInterceptor(createLoggingInterceptor())
                            .retryOnConnectionFailure(true)  // 自动重试
                            .connectTimeout(30, TimeUnit.SECONDS)  // 连接超时
                            .writeTimeout(30, TimeUnit.SECONDS)    // 写超时
                            .readTimeout(30, TimeUnit.SECONDS)     // 读取超时
                            .build();

                    retrofit = new Retrofit.Builder()
                            .baseUrl(BASE_URL)
                            .client(okHttpClient)
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();
                }
            }
        }
        return retrofit;
    }

    // 创建日志拦截器
    private static HttpLoggingInterceptor createLoggingInterceptor() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);  // 打印请求和响应的所有信息
        return interceptor;
    }

    // 创建请求拦截器，添加 token
    private static Interceptor createRequestInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                // 获取请求
                okhttp3.Request request = chain.request();
                if (!request.url().encodedPath().equals("/login")) {  // 排除 /login 请求
                    // 从 SharedPreferences 获取 token
                    TokenManager tokenManager = new TokenManager(MyApplication.getContext());
                    String token = tokenManager.getToken();

                    if (token != null) {
                        // 在请求头中添加 Authorization 字段
                        request = request.newBuilder()
                                .addHeader("Authorization", "Bearer " + token)
                                .build();
                    }
                }

                return chain.proceed(request);
            }
        };
    }

    // 创建响应拦截器，统一处理返回结果
    private static Interceptor createResponseInterceptor() {
        return new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response response = chain.proceed(chain.request());
                String responseBody = response.body() != null ? response.body().string() : "";

                // 解析响应数据
                ResponseData<?> responseData = new Gson().fromJson(responseBody, ResponseData.class);

                // 如果返回的是 500 错误，提示联系管理员
                if (responseData != null && responseData.getCode() == 500) {
                    // 弹窗提示
                    showErrorMessage("服务器错误，请联系管理员。");
                }

                // 如果返回的是 200，返回数据
                if (responseData != null && responseData.getCode() == 200) {
                    // 恢复响应体
                    Response.Builder newResponse = response.newBuilder()
                            .body(okhttp3.ResponseBody.create(response.body().contentType(), responseBody));
                    return newResponse.build();
                }

                // 返回原始响应
                return response;
            }
        };
    }

    private static void showErrorMessage(String message) {
        // 你可以在这里做 UI 相关的操作，比如弹窗或 Toast
         LogUtils.e("RetrofitClient", message); // 可以用 Log 打印错误信息
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(MyApplication.getContext(), message, Toast.LENGTH_SHORT).show();
            }
        });
    }

    // 提供公共接口创建方法
    public static <T> T createService(Class<T> serviceClass) {
        return getInstance().create(serviceClass);
    }
}
